package com.example.mall.common.core.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.example.mall.common.core.anotation.ScopeLevel;
import com.example.mall.common.core.exception.ForbiddenException;
import com.example.mall.common.core.exception.UnauthorizedException;
import com.example.mall.common.utils.JwtToken;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Optional;

/**
 * 权限拦截器
 */
public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("/swagger-ui".equals(request.getRequestURI())) {
            System.out.println("-----白名单-----");
            return true;
        }

        Optional<ScopeLevel> scopeLevel = this.getScopeLevel(handler);
        String token = getTokenFromReqeustHeaders(request);
        Optional<Map<String, Claim>> stringClaimMap = JwtToken.verifyToken(token);
        return true;
    }

    private boolean hasPerssion(ScopeLevel scopeLevel, Map<String, Claim> map) {
        Integer sys_evel = scopeLevel.value();
        Integer request_level = map.get("scope").asInt();

        // 校验逻辑
        if (sys_evel > request_level) {
            // 接口权限 大于 请求权限,不能访问
            throw new ForbiddenException(10005);
        }
        return true;
    }

    /**
     * 在请求头取token
     *  前端暂时在headers直接写token字段
     *  - token: xxxxxxxxxxx
     * @return
     */
    private String getTokenFromReqeustHeaders(HttpServletRequest request) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            throw new UnauthorizedException(10004);
        }
        return token;
    }

    /**
     * 获取权限拦截注解
     * @param handler
     * @return
     */
    private Optional<ScopeLevel> getScopeLevel(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            ScopeLevel scopeLevel = handlerMethod.getMethodAnnotation(ScopeLevel.class);
            return Optional.of(scopeLevel);
        }
        return Optional.empty();
    }
}